#include "book.h"

// 全局变量是在static区
int global_variable = 0;

int main(int argc, char ** argv){
    // 父进程调用fork创建子进程的时候，在fork之后就开启了两个进程（内存里）
    // 父进程的fork的返回值是子进程的pid号，而子进程的fork的返回值是0

    static int static_variable = 0;

    pid_t pid, pid1;

    pid = fork();

    if ( pid < 0){
        // error，输出到stderr
        fprintf(stderr, "Fork failed, exiting...");
        return -1;
    }
    else if (pid == 0) {
        pid1 = getpid();
        printf("\e[1;31m================子进程开始================\e[0m\n");
        printf("子进程：pid = %d\n", pid);
        printf("子进程：pid1 = %d\n", pid1);
        printf("子进程：开始休眠\n");
        for (int i=0; i<= 3; i++){
            sleep(1);
            printf("子进程：休眠第%d秒\n", i);
            printf("子进程：global_variable = %d, static_variable = %d\n", global_variable++, static_variable++);
        }
        printf("子进程：结束休眠\n");
        printf("\e[1;31m================子进程结束================\e[0m\n");
    }
    else {
        pid1 = getpid();
        printf("\e[1;32m++++++++++++++++父进程开始++++++++++++++++\e[0m\n");
        printf("父进程：pid = %d\n", pid);
        printf("父进程：pid1 = %d\n", pid1);
        for (int i=0; i<= 3; i++){
            sleep(1);
            printf("父进程：休眠第%d秒\n", i);
            printf("父进程：global_variable = %d, static_variable = %d\n", global_variable--, static_variable--);
        }
        printf("子进程：结束休眠\n");
        wait(NULL);
        printf("父进程：没有取消wait\n");
        printf("\e[1;32m++++++++++++++++父进程结束++++++++++++++++\e[0m\n");
    }

    printf("main：在主程序中 global_variable = %d，static_variable = %d \n",global_variable, static_variable);
    return 0;
}